package webchinese

import (
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"
)

const sendUrl = "http://utf8.sms.webchinese.cn/"

type Config struct {
	User string
	Key  string
}
//发送验证码
func (this *Config) SendSms(mobile int64, msg string) (int, string) {
	url := fmt.Sprintf("%s/?Uid=%s&Key=%s&smsMob=%d&smsText=%s", sendUrl, this.User, this.Key, mobile, msg);
	resp, err := http.Get(url)
	defer resp.Body.Close()
	if err != nil {
		return 0, "请求失败"
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return 0, "读取失败"
	}
	num, err := strconv.Atoi(string(body))
	if err != nil {
		return 0, "错误的返回值"
	}
	errMsg := map[int]string{
		-1:  "没有该用户账户",
		-2:  "接口密钥不正确 不是账户登陆密码",
		-21: "MD5接口密钥加密不正确",
		-3:  "短信数量不足",
		-11: "该用户被禁用",
		-14: "短信内容出现非法字符",
		-4:  "手机号格式不正确",
		-41: "手机号码为空",
		-42: "短信内容为空",
		-51: "短信签名格式不正确, 接口签名格式为：【签名内容】",
		-6:  "IP限制,大于0 短信发送数量"}
	if num < 0 {
		return num, errMsg[num]
	}
	return num, ""
}

// result 短信数目 ,错误
func (this *Config) GetNum() (int, error) {
	url := fmt.Sprintf("http://www.smschinese.cn/web_api/SMS/?Action=SMS_Num&Uid=%s&Key=%s", this.User, this.Key);
	resp, err := http.Get(url)
	defer resp.Body.Close()
	if err != nil {
		return 0, errors.New("请求失败")
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return 0, errors.New("读取失败")
	}
	num, err := strconv.Atoi(string(body))
	if err != nil {
		return 0, errors.New("错误的返回值" + err.Error())
	}
	return num, nil
}
